import grok

from zope.app.authentication.principalfolder import PrincipalFolder, InternalPrincipal
from zope.app.authentication.session import SessionCredentialsPlugin
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope import schema
from zope.interface import Interface

grok.templatedir('admin_templates')

def setup_authentication(pau):
    """
        Factory function to setup the  Pluggable Authentication Utility
        
        @pau: instance of PluggableAuthentication class
    """
    pau['principals'] = PrincipalFolder()
    pau.authenticatorPlugins = ('principals',)
    
    principals = pau['principals']
    principal = InternalPrincipal("pippo", "pippo", "Carl Rubens",
                                  passwordManagerName='SHA1')
    principals['pippo'] = principal

    permission_mngr = IPrincipalPermissionManager(grok.getSite())
    permission_mngr.grantPermissionToPrincipal('biro.Admin', principals.prefix + "pippo")

    pau['session'] = session = SessionCredentialsPlugin()
    
    session.loginpagename = 'login' # the page to redirect for login
    session.loginfield = 'form.login'
    session.passwordfield = 'form.password'
    # configuration of the credentials plugin
    pau.credentialsPlugins = ('No Challenge if Authenticated', 'session',)
    print "CALLED"
    
    
class BiroAdminPermission(grok.Permission):
    """
        Permission to admin a biro Application
    """
    grok.name("biro.Admin")
    

class ILoginForm(Interface):
    login = schema.BytesLine(title=u'Username', required=True)
    password = schema.Password(title=u'Password', required=True)
    
class Login(grok.Form):
    grok.context(Interface)
#    template = grok.PageTemplateFile('admin_templates/login.pt')
#    grok.template('login.pt')
#    grok.require('zope.Public')

    form_fields = grok.AutoFields(ILoginForm)

    @grok.action('login')
    def handle_login(self, **data):
        import pdb; pdb.set_trace( )
        self.redirect(self.request.form.get('camefrom', ''))
        
        
class Minollo(grok.View):
    grok.context(Interface)
    def update(self):
        import pdb; pdb.set_trace()
        return None
        
    def render(self):
        return str(self.request.principal)
